//
//  ZFActivityView.m
//  components
//
//  Created by linzaifei on 2021/7/13.
//

#import "ZFActivityView.h"
#import "UIView+category.h"
#define ZFWeakSelf __weak typeof(self) weakSelf = self
#define ZFStrongSelf __strong typeof(weakSelf) strongSelf = weakSelf;
@interface ZFActivityView()
@property(nonatomic,strong)ZFActivityBackgroundView *backgroundView;
@property(nonatomic,strong)ZFActivityBackgroundView *contentView;

@property(nonatomic,copy)NSMutableArray <__kindof NSLayoutConstraint *> * constraints;
@end

@implementation ZFActivityView
- (instancetype)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        [self commonInit];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if ((self = [super initWithCoder:aDecoder])) {
        [self commonInit];
    }
    return self;
}

- (id)initWithView:(UIView *)view {
    NSAssert(view, @"View must not be nil.");
    return [self initWithFrame:view.bounds];
}
-(void)commonInit{
    _animationType = ActivityAnimationFade;
    _duration = 0.3;
    _needRemoveSuperView = YES;
    [self setupViews];
}
-(void)setupViews{
 
    ZFActivityBackgroundView *backgroundView = [[ZFActivityBackgroundView alloc] initWithFrame:self.bounds];
    backgroundView.style = ZFActivityBackgroundStyleSolidColor;
    backgroundView.backgroundColor = [UIColor clearColor];
    backgroundView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    backgroundView.alpha = 0.f;
    [self addSubview:backgroundView];
    self.backgroundView = backgroundView;
    
    ZFActivityBackgroundView *contentView = [[ZFActivityBackgroundView alloc] init];
    contentView.translatesAutoresizingMaskIntoConstraints = NO;
    contentView.alpha = 0.f;
    contentView.style = ZFActivityBackgroundStyleSolidColor;
    contentView.color = [UIColor clearColor];
    [backgroundView addSubview:contentView];
    self.contentView = contentView;
    
    ZFWeakSelf;    
    [backgroundView addTarget:^(UIGestureRecognizer * _Nonnull x) {
        ZFStrongSelf;
        if (strongSelf.canTouchBackground) {
            [strongSelf hideAnimated:YES];
        }
    }];
    
}





#pragma mark --- 开始、结束、延时动画

///开始动画
-(void)showAnimated:(BOOL)animated{
    if (animated) {
        [self animatingIn:YES withType:self.animationType completion:NULL];
    }else{
        self.contentView.alpha=1.0f;
        self.backgroundView.alpha =1.0f;
    }
}
///结束动画
-(void)hideAnimated:(BOOL)animated{
    if (animated) {
        ZFWeakSelf;
        [self animatingIn:NO withType:self.animationType completion:^(BOOL finished) {
            ZFStrongSelf;
            [strongSelf done];
        }];
    }else{
        [self done];
    }
}
///延迟多久结束
-(void)hideAnimated:(BOOL)animated delay:(NSTimeInterval)delay{
    ZFWeakSelf;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        ZFStrongSelf;
        [strongSelf hideAnimated:animated];
    });
}
///完成
-(void)done{
    self.alpha = 0.0f;
    self.contentView.alpha = 0.f;
    self.backgroundView.alpha =0.f;
    if (self.needRemoveSuperView) {
        [self removeFromSuperview];
    }
}



#pragma mark --- 动画效果
-(void)animatingIn:(BOOL)animatingIn withType:(ActivityAnimation)type  completion:(void(^)(BOOL finished))completion{
    
    ZFWeakSelf;
    if (type==ActivityAnimationPopBottom ||type==ActivityAnimationPopRight || type==ActivityAnimationPopLeft|| type==ActivityAnimationPopTop) {
        
        // 获取约束后的size
        CGSize fittingSize = [self.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
        NSLog(@"%@",NSStringFromCGSize(fittingSize));
        CGAffineTransform hTransfrom = CGAffineTransformMakeTranslation(type==ActivityAnimationPopLeft?-fittingSize.width:fittingSize.width,0);
        CGAffineTransform vTransfrom = CGAffineTransformMakeTranslation(0, type==ActivityAnimationPopBottom?fittingSize.height:-fittingSize.height);
    
        self.contentView.transform = animatingIn? (type==ActivityAnimationPopBottom ||type==ActivityAnimationPopTop)?vTransfrom:hTransfrom :CGAffineTransformIdentity;;
        
        [UIView animateWithDuration:_duration delay:0 usingSpringWithDamping:1.0f initialSpringVelocity:0.f options:UIViewAnimationOptionBeginFromCurrentState animations:^{
            ZFStrongSelf;
            strongSelf.contentView.transform = animatingIn? CGAffineTransformIdentity:(type==ActivityAnimationPopBottom ||type==ActivityAnimationPopTop)?vTransfrom:hTransfrom;
          
            CGFloat alpha = animatingIn ? 1.f : 0.f;
            strongSelf.contentView.alpha = alpha;
            strongSelf.backgroundView.alpha = alpha;
        } completion:completion];
        
        return;
    }
    
    
    if (type == ActivityAnimationZoom) {
        type = animatingIn ? ActivityAnimationZoomIn : ActivityAnimationZoomOut;
    }

    CGAffineTransform small = CGAffineTransformMakeScale(0.5f, 0.5f);
    CGAffineTransform large = CGAffineTransformMakeScale(1.5f, 1.5f);
    
    if(animatingIn && self.contentView.alpha==0.f && type == ActivityAnimationZoomIn){
        self.contentView.transform = small;
    }else if(animatingIn && self.contentView.alpha==0.f && type == ActivityAnimationZoomOut){
        self.contentView.transform = large;
    }
    [UIView animateWithDuration:_duration delay:0 usingSpringWithDamping:1.0f initialSpringVelocity:0.f options:UIViewAnimationOptionBeginFromCurrentState animations:^{
        ZFStrongSelf;
        if(animatingIn){
            strongSelf.contentView.transform = CGAffineTransformIdentity;
        } else if (!animatingIn && type == ActivityAnimationZoomIn) {
            strongSelf.contentView.transform = large;
        } else if (!animatingIn && type == ActivityAnimationZoomOut) {
            strongSelf.contentView.transform = small;
        }
        CGFloat alpha = animatingIn ? 1.f : 0.f;
        strongSelf.contentView.alpha = alpha;
        strongSelf.backgroundView.alpha = alpha;
    } completion:completion];
}

#pragma mark --- setter 、getter
- (NSArray<__kindof NSLayoutConstraint *> *)constraints{
    if (!_constraints) {
        _constraints = [NSMutableArray array];
    }
    return _constraints;
}

- (void)setAnimationType:(ActivityAnimation)animationType{
    if (_animationType != animationType) {
        _animationType = animationType;
        [self layoutContentView];
    }
}

-(void)layoutContentView{
    [self removeConstraints:self.constraints];
    if (self.animationType == ActivityAnimationPopBottom) {
        [self layoutBotttom];
    }else if (self.animationType == ActivityAnimationPopRight) {
        [self layoutRight];
    }else if (self.animationType == ActivityAnimationPopTop) {
        [self layoutTop];
    }else if (self.animationType == ActivityAnimationPopLeft) {
        [self layoutLeft];
    }else{
        [self layoutCenter];
    }
}




#pragma mark --- 布局中间、底部等
/***
 |------------------|
 |                         |
 |   |-------------|  |
 |   |      中间     |  |
 |   |-------------|  |
 |                         |
 |------------------|
 */
///从中间布局
-(void)layoutCenter{
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-40-[contentView]-40-|" options:0 metrics:0 views:@{@"contentView":self.contentView}]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.contentView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[contentView(>=100)]" options:0 metrics:0 views:@{@"contentView":self.contentView}]];
}

///底部布局
-(void)layoutBotttom{
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[contentView]-0-|" options:0 metrics:0 views:@{@"contentView":self.contentView}]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.contentView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1 constant:0]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[contentView(>=150)]" options:0 metrics:0 views:@{@"contentView":self.contentView}]];
}
-(void)layoutRight{
    
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[contentView]-0-|" options:0 metrics:0 views:@{@"contentView":self.contentView}]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.contentView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeRight multiplier:1 constant:0]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[contentView(>=100)]" options:0 metrics:0 views:@{@"contentView":self.contentView}]];
}
-(void)layoutTop{
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[contentView]-0-|" options:0 metrics:0 views:@{@"contentView":self.contentView}]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.contentView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1 constant:0]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[contentView(>=100)]" options:0 metrics:0 views:@{@"contentView":self.contentView}]];
}
-(void)layoutLeft{
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[contentView]-0-|" options:0 metrics:0 views:@{@"contentView":self.contentView}]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.contentView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeft multiplier:1 constant:0]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[contentView(>=100)]" options:0 metrics:0 views:@{@"contentView":self.contentView}]];
}
@end
